package cn.itsource.mq.delay;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 消费者
 */
public class DelayConsumer {
    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("mq-delay-consumer-group");
        consumer.setNamesrvAddr("127.0.0.1:9876");//2设置mq地址 连接nameServer的ip和端口号
        consumer.subscribe("delay-topic", "delay-tag");//3订阅消息

        //4注册消息监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                msgs.forEach(m->{
                    byte[] msgByteArray = m.getBody();//拿到消息
                    try {
                        //处理消息                          消息集合        mq的上下文
                        String messsageStr = new String(msgByteArray, "utf-8");
                        System.out.println(messsageStr);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                });
                //消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                //过一段时间再消费
                //return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });

        //5启动start  这个必须在监听器后执行
        consumer.start();
    }
}
